/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.view;

import com.jspx.boot.EnvFactory;
import com.jspx.sioc.BeanFactory;
import com.jspx.txweb.IRole;
import com.jspx.txweb.IUserSession;
import com.jspx.txweb.annotation.HttpMethod;
import com.jspx.txweb.annotation.Safety;
import com.jspx.txweb.dao.MemberTreeDAO;
import com.jspx.txweb.dao.PermissionDAO;
import com.jspx.txweb.dao.TreeItemDAO;
import com.jspx.txweb.dao.impl.TreeItemDAOImpl;
import com.jspx.txweb.env.TXWebIoc;
import com.jspx.txweb.support.ActionSupport;
import com.jspx.txweb.table.MemberTree;
import com.jspx.txweb.table.TreeItem;
import com.jspx.utils.ArrayUtil;
import com.jspx.utils.StringUtil;
import com.jspx.boot.sign.UserType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: chenYuan
 * Date: 2008-9-21
 * Time: 14:52:21
 *
 */
@HttpMethod(caption="树结构")
public class TreeView  extends ActionSupport
{
    final private static Logger log = LoggerFactory.getLogger(TreeView.class);
    private String inputName = "nodeId";
    private String input = null; //输入框 text  jspx tree 不使用   radio
    private boolean useLimb = false; //是否使用叶子部分
    private boolean assigner = false; //默认方式 true:按照分配的权限读取
    protected long uid = -1;//会员ID 不为空,显示用户树

    public TreeView()
    {

    }

    protected TreeItemDAO treeItemDAO;
    @Safety(request = false)
    public void setTreeItemDAO(TreeItemDAO treeItemDAO)
    {
        this.treeItemDAO = treeItemDAO;
    }

    protected MemberTreeDAO memberTreeDAO;
    @Safety(request = false)
    public void setMemberTreeDAO(MemberTreeDAO memberTreeDAO)
    {
        this.memberTreeDAO = memberTreeDAO;
    }

    public String getNamespace()
    {
        return treeItemDAO.getNamespace();
    }

    public boolean isAssigner()
    {
        return assigner;
    }

    public void setAssigner(boolean assigner)
    {
        this.assigner = assigner;
    }

    public String getInput()
    {
        return input;
    }

    @Safety
    public void setInput(String input)
    {
        this.input = input;
    }

    public boolean isUseLimb() {
        return useLimb;
    }

    public void setUseLimb(boolean useLimb) {
        this.useLimb = useLimb;
    }

    public String getInputName()
    {
        return inputName;
    }

    @Safety
    public void setInputName(String inputName)
    {
        this.inputName = inputName;
    }

    public boolean isShow()
    {
        return treeItemDAO.isShow();
    }

    public void setShow(boolean show)
    {
        treeItemDAO.setShow(show);
    }

    protected String nodeId;

    @Safety(length = 50,level = 3)
    public void setNodeId(String nodeId)
    {
            this.nodeId = nodeId;
    }

    public long getUid() {
        return uid;
    }


    public void setUid(long uid) {
        this.uid = uid;
    }

    /**
     * 不会识别多个方法 ,同名请求参数重复设置不可控
     * @param nodeIds 节点id
     */
    @Safety(max=120,level = 3)
    public void setNodeIds(String[] nodeIds)
    {
        this.nodeId = ArrayUtil.toString(nodeIds, StringUtil.SEMICOLON);
    }

    /**
     *
     * @return 得到选项
     */
    public String getOptionList()
    {
        if (assigner)
        {
            IUserSession userSession = (IUserSession)getUserSession();
            if (!isGuest() && userSession.getRole(treeItemDAO.getNamespace()).getUserType() < UserType.ADMINISTRATOR)
            {
                treeItemDAO.setChecked(memberTreeDAO.getMemberTreeSplitString(userSession.getUid()));
            } else treeItemDAO.setChecked(ArrayUtil.emptyString);
        } else
        {
            treeItemDAO.setChecked(ArrayUtil.emptyString);
        }

        Map<String, String> map = treeItemDAO.getSelectTreeItemMap("....|-");
        StringBuilder sb = new StringBuilder();
        for (String k:map.keySet())
        {
            sb.append(k).append(":").append(map.get(k)).append(StringUtil.SEMICOLON);
        }
        map.clear();
        return sb.toString();
    }

    /**
     *
     * @return 树XML
     * @throws Exception
     */
    public String getTreeItemXml() throws Exception {
        if (StringUtil.isNULL(nodeId)) nodeId = ArrayUtil.toString(getArray("nodeId",true),StringUtil.SEMICOLON);
        treeItemDAO.setSelected(nodeId);
        treeItemDAO.setInput(input);
        treeItemDAO.setUseLimb(useLimb);
        return treeItemDAO.toXMLString();
    }

    /**
     *  得到平铺方式的json数据
     * @return 树代码
     * @throws Exception
     */
    public String getTreeSrc() throws Exception {
        if (uid>0)
            nodeId = memberTreeDAO.getMemberTreeSplitString(uid);
        else if (!StringUtil.hasLength(nodeId))
            nodeId = ArrayUtil.toString(getArray("nodeId",true),StringUtil.SEMICOLON);
        treeItemDAO.setSelected(nodeId);
        treeItemDAO.setInput(input);
        treeItemDAO.setUseLimb(useLimb);
        treeItemDAO.setChecked(ArrayUtil.emptyString);
        return treeItemDAO.getTreeSrc(TreeItemDAOImpl.Type_json);
    }

    /**
     * 得到递进方式的json数据
     * @return
     * @throws Exception
     */
    public String getJsonTreeSrc() throws Exception {
        if (uid>0)
            nodeId = memberTreeDAO.getMemberTreeSplitString(uid);
        else if (!StringUtil.hasLength(nodeId))
            nodeId = ArrayUtil.toString(getArray("nodeId",true),StringUtil.SEMICOLON);
        treeItemDAO.setSelected(nodeId);
        treeItemDAO.setInput(input);
        treeItemDAO.setUseLimb(useLimb);
        return treeItemDAO.getTreeSrc(TreeItemDAOImpl.Type_jsonTree);
    }

    /**
     * 得到递进方式的json数据
     * @return
     * @throws Exception
     */
    public String getRoleTreeSrc() throws Exception {
        if (uid>0)
            nodeId = memberTreeDAO.getMemberTreeSplitString(uid);
        else if (!StringUtil.hasLength(nodeId))
            nodeId = ArrayUtil.toString(getArray("nodeId",true),StringUtil.SEMICOLON);
        treeItemDAO.setSelected(nodeId);
        treeItemDAO.setInput(input);
        treeItemDAO.setUseLimb(useLimb);
        return treeItemDAO.getTreeSrc(TreeItemDAOImpl.Type_roleJson);
    }

    /**
     * 得到递进方式的json数据
     * @return
     * @throws Exception
     */
    public String getRoleJsonTreeSrc() throws Exception {
        if (uid>0)
            nodeId = memberTreeDAO.getMemberTreeSplitString(uid);
        else if (!StringUtil.hasLength(nodeId))
            nodeId = ArrayUtil.toString(getArray("nodeId",true),StringUtil.SEMICOLON);
        treeItemDAO.setSelected(nodeId);
        treeItemDAO.setInput(input);
        treeItemDAO.setUseLimb(useLimb);
        return treeItemDAO.getTreeSrc(TreeItemDAOImpl.Type_roleJsonTree);
    }
    /**
     *得到包含角色信息的树结构（数据为平铺方式）,资源占用比较大
     * @return 树代码
     * @throws Exception
     */
    public String getRoleTree() throws Exception {
        BeanFactory beanFactory = EnvFactory.getBeanFactory();
        PermissionDAO permissionDAO = (PermissionDAO)beanFactory.getBean(TXWebIoc.permissionDAO,treeItemDAO.getNamespace());
        List<TreeItem> treeItemList = treeItemDAO.createRepairTreeRole(permissionDAO.getRoleList());
        return TreeItemDAOImpl.getJson(treeItemList,"role",null,null,treeItemDAO.getNamespace());
    }

    /**
     *得到包含角色信息的树结构（数据为递进方式）,资源占用比较大
     * @return 树代码
     * @throws Exception
     */
    public String getRoleJsonTree() throws Exception {
        BeanFactory beanFactory = EnvFactory.getBeanFactory();
        PermissionDAO permissionDAO = (PermissionDAO)beanFactory.getBean(TXWebIoc.permissionDAO,treeItemDAO.getNamespace());
        List<TreeItem> treeItemList = treeItemDAO.createRepairTreeRole(permissionDAO.getRoleList());
        return TreeItemDAOImpl.getJsonTree(treeItemList,"role",null,null,treeItemDAO.getNamespace()).toString(4);
    }

    /**
     *
     * @return 用户树代码,提供后台控制使用
     */
    public String getUserTreeSrc()
    {
        IUserSession userSession = (IUserSession)getUserSession();
        if (!isGuest() && userSession.getRole(treeItemDAO.getNamespace()).getUserType() < UserType.ADMINISTRATOR)
        {
            treeItemDAO.setChecked(memberTreeDAO.getMemberTreeSplitString(userSession.getUid()));
        } else treeItemDAO.setChecked(ArrayUtil.emptyString);
        if (!StringUtil.hasLength(nodeId))
            nodeId = ArrayUtil.toString(getArray("nodeId",true),StringUtil.SEMICOLON);

        treeItemDAO.setSelected(nodeId);
        treeItemDAO.setInput(input);
        treeItemDAO.setUseLimb(useLimb);
        return treeItemDAO.getTreeSrc(TreeItemDAOImpl.Type_json);
    }


    /**
     * 更具角色得到角色树
     * @return
     */
    public String getRoleNodeTreeSrc() {
        IRole role = getRole();
        if (StringUtil.isNULL(nodeId)) nodeId = ArrayUtil.toString(getArray("nodeId",true),StringUtil.SEMICOLON);
        treeItemDAO.setSelected(nodeId);
        treeItemDAO.setInput(input);
        treeItemDAO.setUseLimb(useLimb);
        treeItemDAO.setChecked(treeItemDAO.getRoleNodeIds(role.getId()));
        return treeItemDAO.getTreeSrc(TreeItemDAOImpl.Type_json);
    }


    /**
     *
     * @return 得到树代码
     * @throws Exception
     */
    public String getChildSrc()  {
        if (StringUtil.isNULL(nodeId)) nodeId = ArrayUtil.toString(getArray("nodeId",true),StringUtil.SEMICOLON);
        treeItemDAO.setSelected(nodeId);
        treeItemDAO.setInput(input);
        treeItemDAO.setUseLimb(useLimb);
        return treeItemDAO.getJsonChildSrc(nodeId);
    }


    /**
     *
     * @return 得到第一个节点
     */
    public String getFirstNodeId()
    {
        if (!StringUtil.hasLength(nodeId))
        {
            return "root";
        }
        if (!nodeId.contains(StringUtil.SEMICOLON))
        {
            return nodeId;
        }
        return StringUtil.substringBefore(nodeId,StringUtil.SEMICOLON);
    }

    /**
     *
     * @return 导出树
     */
    public String getTreeExport()
    {
        Map<String, String> map = treeItemDAO.getSelectTreeItemMap("....|-");
        StringBuilder sb = new StringBuilder();
        for (String k:map.keySet())
        {
            sb.append(k).append(":").append(map.get(k)).append(StringUtil.CRLF);
        }
        map.clear();
        return sb.toString();
    }

    /**
     * 得到节点路径
     * @return 节点列表
    */
    public List<TreeItem> getTreeItemPath() throws Exception
    {
        return treeItemDAO.getTreeItemPath(getFirstNodeId());
    }

    /**
     * 得到节点
     * @return String
     */
    public String getNodeId()
    {
        if (!StringUtil.isNULL(nodeId)) return nodeId;
        return "root";
    }

    /**
     *
     * @return 得到当前节点
     */
    public TreeItem getTreeItem()
    {
        if (treeItemDAO==null)
        {
            log.error("treeItemDAO not config ,没有配置treeItemDAO");
        }
        TreeItem result = treeItemDAO.getTreeItem(getFirstNodeId());
        if (result == null)
            return treeItemDAO.getRootTreeItem();
        return result;
    }

    /**
     *
     * @return 得到上级目录
     * @throws Exception
     */
    public List<TreeItem> getParentChildTreeItem() throws Exception
    {
        TreeItem treeItem = getTreeItem();
        if (TreeItemDAOImpl.rootId.equalsIgnoreCase(treeItem.getParentNodeId()))
        {
            return treeItemDAO.getChildTreeItem(treeItem.getNodeId());
        }
        return treeItemDAO.getChildTreeItem(getTreeItem().getParentNodeId());
    }

    public TreeItem getParentTreeItem() throws Exception
    {
        TreeItem treeItem = getTreeItem();
        if (treeItem==null) return treeItemDAO.getRootTreeItem();
        if (TreeItemDAOImpl.rootId.equalsIgnoreCase(treeItem.getNodeId())) return treeItem;
        return treeItemDAO.getTreeItem(treeItem.getParentNodeId());
    }


    /**
     * 得到root节点后的第一个节点，就是主菜单节点
     * @return
     * @throws Exception
     */
    public TreeItem getFirstParentTreeItem(String nodeId) throws Exception
    {
        return treeItemDAO.getFirstParentTreeItem(nodeId);
    }

    /**
     *
     * @return 得到子节点列表
     */
    public List<TreeItem> getChildTreeItem() throws Exception
    {
        String nid;
        if (nodeId != null && !nodeId.contains(StringUtil.SEMICOLON))
        {
            nid = nodeId;
        } else
        {
            nid = StringUtil.substringBefore(nodeId, StringUtil.SEMICOLON);
        }
        return treeItemDAO.getChildTreeItem(nid);
    }

    /**
     *
     * @param nodeId  节点id
     * @return 得到子
     */
    public List<TreeItem> getChildTreeItem(String nodeId)
    {
        return treeItemDAO.getChildTreeItem(nodeId);
    }

    /**
     * @return 得到用户数
     */
    public String[] getMemberTreeArray()
    {
        return memberTreeDAO.getMemberTreeArray(uid);
    }

    /**
     *
     * @return 得到子节点列表
     */
    public List<TreeItem> getTreeList()
    {
        return treeItemDAO.getList();
    }

    public TreeItem getTreeItem(String nodeId)
    {
        return treeItemDAO.getTreeItem(nodeId);
    }


    public boolean isLimb()
    {
        return isLimb(nodeId);
    }

    public boolean isLimb(String nodeId)
    {
        return treeItemDAO.isLimb(nodeId);
    }

    public boolean isManager(String nodeId,int roleId,long uid)
    {
        return treeItemDAO.isManager(nodeId,roleId,uid);
    }

    /**
     *
     * @return 得到用户数
     */
    public  List<MemberTree> getManTree()
    {
        return memberTreeDAO.getMemberTree(uid);
    }


    /**
     * 常用的单元方法，判断一个列表里边是否存在自定的id
     * @param list
     * @param nodeId
     * @return
     */
    static public TreeItem  getFindTreeItem(List<TreeItem> list,String nodeId)
    {
        if (StringUtil.isNULL(nodeId)||list.isEmpty()) return null;
        for (TreeItem treeItem : list)
        {
            if (treeItem.getNodeId().equalsIgnoreCase(nodeId))
            {
                return treeItem;
            }
        }
        return null;
    }

    @Override
    public String execute() throws Exception
    {
        TreeItem treeItem = getTreeItem();
        if (treeItem == null) treeItem = new TreeItem();
        put("nodeId", getFirstNodeId());
        put("treeItem", treeItem);
        return super.execute();
    }
}